﻿using System;

namespace Fluent.HtmlModel
{
    public class Expander<TPage> : HtmlElement<TPage>
        where TPage : WebPageBase
    {
        public HtmlElement<TPage> ExpandeContentContainer { get; private set; }
        public HtmlElement<TPage> CollapseContentContainer { get; private set; }
        public Action OnExpanded { get; private set; }
        public Action OnCollapsed { get; private set; }

        public Expander(TPage containerPageObj, Finder finder,
                Finder expandeContentContainerBy, Action onExpanded = null,
                Finder collapseContentContainerBy = null, Action onCollapsed = null)
            : base(containerPageObj, finder)
        {
            this.ExpandeContentContainer = new HtmlElement<TPage>(this.Page, expandeContentContainerBy);

            if (collapseContentContainerBy != null)
            {
                this.CollapseContentContainer = new HtmlElement<TPage>(this.Page, collapseContentContainerBy);
            }

            this.OnExpanded = onExpanded;
            this.OnCollapsed = onCollapsed;
        }
        
        public override TPage Click()
        {
            if (!this.ExpandeContentContainer.IsVisible())
            {
                this.Expand();
            }
            else if (!this.CollapseContentContainer.IsVisible())
            {
                this.Collapse();
            }

            return this.Page;
        }

        public TPage Expand()
        {
            if (!this.ExpandeContentContainer.IsVisible())
            {
                base.CenterOnView();
                base.Click();
                this.ExpandeContentContainer.WaitShow();
            }

            if (this.OnExpanded != null)
            {
                this.OnExpanded();
            }

            return this.Page;
        }

        public TPage Collapse()
        {
            if (!this.CollapseContentContainer.IsVisible())
            {
                base.CenterOnView();
                base.Click();
                this.CollapseContentContainer.WaitShow();
            }

            if (this.OnCollapsed != null)
            {
                this.OnCollapsed();
            }

            return this.Page;
        }
    }
}